"""
认证验证路由
处理邮箱验证相关的请求
实现系统级别的全局验证，管理员验证后所有用户均可访问
"""
from flask import Blueprint, render_template, request, jsonify, redirect, url_for
from utils.auth_verifier import AuthVerifier

auth_bp = Blueprint('auth', __name__)

# 全局验证器实例
verifier = None


def init_auth_verifier(app):
    """初始化验证器"""
    global verifier
    verifier = AuthVerifier(app)
    return verifier


@auth_bp.route('/verify')
def verify_page():
    """验证页面"""
    if not verifier:
        return "验证系统未初始化", 500
    
    # 检查验证状态
    status = verifier.check_verification_status()
    
    # 检查邮件配置
    email_configured = verifier.is_email_configured()
    admin_email = verifier.get_admin_email()
    
    return render_template(
        'auth/verify.html',
        status=status,
        email_configured=email_configured,
        admin_email=admin_email
    )


@auth_bp.route('/send-code', methods=['POST'])
def send_code():
    """发送验证码"""
    if not verifier:
        return jsonify({
            'success': False,
            'message': '验证系统未初始化'
        }), 500
    
    # 检查邮件配置
    if not verifier.is_email_configured():
        return jsonify({
            'success': False,
            'message': '邮件配置不完整，请配置环境变量后重启系统'
        }), 400
    
    try:
        # 生成验证码
        code = verifier.generate_code()
        
        # 保存验证码
        verifier.save_verification_code(code)
        
        # 发送邮件
        admin_email = verifier.get_admin_email()
        if verifier.send_verification_email(admin_email, code):
            return jsonify({
                'success': True,
                'message': f'验证码已发送到 {admin_email}，请查收邮件'
            })
        else:
            return jsonify({
                'success': False,
                'message': '验证码发送失败，请检查邮件配置'
            }), 500
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            'success': False,
            'message': f'发送验证码时出错: {str(e)}'
        }), 500


@auth_bp.route('/verify-code', methods=['POST'])
def verify_code():
    """验证验证码"""
    if not verifier:
        return jsonify({
            'success': False,
            'message': '验证系统未初始化'
        }), 500
    
    data = request.get_json()
    code = data.get('code', '').strip()
    
    if not code:
        return jsonify({
            'success': False,
            'message': '请输入验证码'
        }), 400
    
    try:
        # 验证验证码
        result = verifier.verify_code(code)
        
        if result['success']:
            # 保存验证成功记录（全局解锁系统）
            verifier.save_verification_success()
            
            return jsonify({
                'success': True,
                'message': '验证成功！系统已解锁，所有用户均可访问',
                'redirect': url_for('main.index')
            })
        else:
            return jsonify({
                'success': False,
                'message': result['message']
            }), 400
    except Exception as e:
        import traceback
        traceback.print_exc()
        return jsonify({
            'success': False,
            'message': f'验证时出错: {str(e)}'
        }), 500


@auth_bp.route('/check-status')
def check_status():
    """检查验证状态"""
    if not verifier:
        return jsonify({
            'success': False,
            'message': '验证系统未初始化'
        }), 500
    
    try:
        status = verifier.check_verification_status()
        return jsonify({
            'success': True,
            'status': status
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'message': f'检查状态时出错: {str(e)}'
        }), 500

